package br.com.ss.centralaamar.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import br.com.ss.centralaamar.exceptions.ValidationException;
import br.com.ss.centralaamar.model.dao.EleitorDao;
import br.com.ss.centralaamar.model.dao.LocalDao;
import br.com.ss.centralaamar.model.entity.Eleitor;
import br.com.ss.centralaamar.model.entity.Local;

@Component("localController")
@Scope("session")
public class LocalController {

	private static final Logger logger = LoggerFactory
			.getLogger(LocalController.class);

	private Local local = new Local();
	private List<Local> locais;
	private List<Eleitor> eleitores;
	private Local selected;

	@Autowired
	private LocalDao localDao;
	@Autowired
	private EleitorDao eleitorDao;

	public String getMessage() {
		logger.debug("Returning message from local home bean");
		return "Hello from Spring";
	}

	public Local getLocal() {
		return local;
	}

	public void save() {
		try {
			// LocalValidator.validarCampos(local);

			this.local.setNome(this.local.getNome().toUpperCase());

			if (this.local.getId() == 0)
				localDao.save(this.local);
			else
				localDao.merge(this.local);
			this.local = new Local();
			this.locais = localDao.list();
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso",
							"Dados salvos com sucesso !"));
		} catch (ValidationException e) {
			System.out.println(e.getMessage());
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN, "Warnning", e
							.getMessage()));
		} catch (Exception e) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", e
							.getMessage()));
		}

	}

	public String listAll() {
		this.locais = localDao.list();
		return "listaAllLocal";
	}

	public String editar() {
		this.local = this.selected;
		this.selected = new Local();
		return "edit";
	}

	public void remove() {
		this.local = this.selected;
		localDao.remove(this.local);
		this.locais = localDao.list();

	}

	public List<Local> getLocais() {
		if (this.locais == null)
			this.locais = localDao.list();
		return this.locais;
	}

	public void setLocais(List<Local> locais) {
		this.locais = locais;
	}

	public String clean() {
		this.local = new Local();
		return "edit";
	}

	public Local getSelected() {
		return selected;
	}

	public void setSelected(Local selected) {
		this.selected = selected;
	}

	public void setLocal(Local local) {
		this.local = local;
	}

	public void print() {
		ByteArrayOutputStream byteOutPutStream = new ByteArrayOutputStream();

		try {
			FacesContext facesContext = FacesContext.getCurrentInstance();

			HttpServletResponse response = (HttpServletResponse) facesContext
					.getExternalContext().getResponse();

			ServletContext servletContext = (ServletContext) facesContext
					.getExternalContext().getContext();

			String pathJasper = servletContext
					.getRealPath("/WEB-INF/relatorio/listagemLocal.jasper");

			JasperPrint preencher = JasperFillManager.fillReport(pathJasper,
					null, new JRBeanCollectionDataSource(this.locais));

			JasperExportManager.exportReportToPdfStream(preencher,
					byteOutPutStream);

			System.out.println("Size of OutPut: " + byteOutPutStream.size());
			response.setContentLength(byteOutPutStream.size());
			response.setContentType("application/pdf");

			ServletOutputStream servletOutPutStream = response
					.getOutputStream();
			servletOutPutStream.write(byteOutPutStream.toByteArray(), 0,
					byteOutPutStream.size());

			servletOutPutStream.flush();
			servletOutPutStream.close();

			FacesContext.getCurrentInstance().responseComplete();

		} catch (JRException jrex) {
			jrex.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}